package com.vekslers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class StringTool {
	protected static Pattern patt = Pattern.compile("^\\s+$"); // Match only
																// string built
																// from nothing
																// but
																// whitespace
																// characters...

	/**
	 * Check if Object is null or of string length 0
	 * 
	 * @param s
	 * @return true if it's empty
	 */
	public static boolean isEmpty(Object o) {
		if (o == null || String.valueOf(o).length() == 0)
			return true;

		return false;
	}

	/**
	 * Check if Object is not null or of string length 0
	 * 
	 * @param s
	 * @return true if it's not empty
	 */
	public static boolean isNotEmpty(Object o) {
		return !isEmpty(o);
	}

	/**
	 * Either{@link #isEmpty(String)} is true or string contains nothing but
	 * whitespace chars.
	 * 
	 * @see TestStringUtil
	 * 
	 */
	public static boolean isBlank(String s) {
		if (isEmpty(s))
			return true;

		Matcher matcher = patt.matcher(s);
		if (matcher.matches())
			return true;

		return false;
	}

	public static String convertStreamToString(InputStream is) throws IOException {
		/*
		 * To convert the InputStream to String we use the Reader.read(char[]
		 * buffer) method. We iterate until the Reader return -1 which means
		 * there's no more data to read. We use the StringWriter class to
		 * produce the string.
		 */
		if (is != null) {
			Writer writer = new StringWriter();

			char[] buffer = new char[1024];
			try {
				Reader reader = new BufferedReader(new InputStreamReader(is,
						"UTF-8"));
				int n;
				while ((n = reader.read(buffer)) != -1) {
					writer.write(buffer, 0, n);
				}
			} finally {
				is.close();
			}
			return writer.toString();
		} else {
			return "";
		}
	}

	/**
	 * {@link #isEmpty(String)} is False and string does not contains nothing
	 * but whitespace chars.
	 * 
	 * @see TestStringUtil
	 * 
	 */
	public static boolean isNotBlank(String s) {
		return !isBlank(s);
	}

	public static void main(String[] args) {
		System.out.println(isEmpty(null));
		System.out.println(isEmpty(""));
	}
}
